#!/bin/bash

source $SELF_PATH/env.sh

ALT_VER="p10"
WGET_PKGS=(config.zip fonts.zip arc-theme.rpm wallpappers.zip deno.zip
           grub2-themes.zip plymouth-themes.zip selene.zip vimix-icon-theme.zip
           eepm.rpm yt-dlp.zip shadowsocks.zip ssh.zip bun.zip config_laptop.zip
           smplayer-icons.zip)

REPO_PKGS=(libssl53 libssl-devel gcc gcc-c++ gdb gcc-gdb-plugin
           automake libffi-devel libyaml-devel libyaml-cpp-devel libncurses-devel
           zlib-devel diffutils libtool bison autoconf libreadline7 patch curl
           libsqlite3-devel sqlite3 libgdbm-devel git neovim alacritty kde5-profile
           kde5-kate kde5-konsole thunar thunar-archive-plugin thunar-volman-plugin
           xfce4-settings qt5ct Kvantum qbittorrent flatpak snapd wireguard-tools-wg-quick
           xsel micro docker-ce x-cursor-themes-dmz smplayer smplayer-themes smplayer-skins
           mpv)

# System paths
GRUB_CFG_PATH="/etc/sysconfig/grub2"
GRUB_THEME_DIR="/boot/grub/themes"
PLYMOUTH_THEME_DIR="/usr/share/plymouth/themes"
ROOT_CONFIG_PATH="/root/.config"
WALLPAPPERS_DIR="/usr/share/wallpapers/MyWallpappers"
FONTS_DIR="/usr/share/fonts/MyFonts"
SS_CONFIG_DIR="/etc/shadowsocks"
FIX_GRUB_PATH="${SYSTEM_BIN}/fix-grub"
SMPLAYER_THEME_DIR="/usr/share/smplayer/themes"

# User paths
USER_CONFIG_PATH="/home/${LOCAL_USER}/.config"
USER_PICTURES_PATH=$(su - -c "xdg-user-dir PICTURES" ${LOCAL_USER})
USER_PROFILE_PATH="/home/${LOCAL_USER}/.bash_profile"
KONSOLE_CONFIG_PATH="/home/${LOCAL_USER}/.local/share/konsole"

# Laptop settings
ENABLE_LAPTOP="true"
BOOST="0"
MIN_FREQ="800000"
MAX_FREQ="1200000"
GOVERNOR="ondemand"

# Make dirs
function make_dirs {
  mkdir -p ./temp ${LOCAL_BIN} ${ROOT_CONFIG_PATH} ${WALLPAPPERS_DIR}\
        ${FONTS_DIR} ${KONSOLE_CONFIG_PATH} ${SSH_DIR} ${SS_CONFIG_DIR}
  echo "export PATH=\"\$PATH:${LOCAL_BIN}\"" >> ${USER_PROFILE_PATH}
  chown -R ${LOCAL_USER}:${LOCAL_USER} ${USER_PROFILE_PATH}
  cd ./temp
}

# Prepare
function prepare() {
  control sudowheel enabled
  apt-get update && apt-get dist-upgrade -y
  apt-get install -y ${REPO_PKGS[@]}
}

# Clean temp dir
function clean_temp_dir {
  cd ..
  rm -rf ./temp
}

# Download files
function download_files {
  for __pkg in ${WGET_PKGS[@]}
  do
    wget --user ${WGET_USER} --password ${WGET_PASSWORD}\
         ${WGET_SERVER}/${ID}/${ALT_BRANCH_ID}/${__pkg}
  done
}

# Install external rpms
function install_ext_rpms {
  for __pkg in ${WGET_PKGS[@]}
  do
    if [[ ${__pkg##*.} == "rpm" ]]; then
      apt-get install -y ${__pkg}
    fi
  done
}

# Unzip
function extract {
  for __pkg in ${WGET_PKGS[@]}
  do
    if [[ ${__pkg##*.} == "zip" ]]; then
      unzip -o -qq -d $(basename "${__pkg}" .zip) ${__pkg}
    fi
  done
}

# Move configs
function move_configs {
  __file_list=($(ls -A))
  for __pkg in ${__file_list[@]}
  do
    if [[ -d ${__pkg} ]]; then
      if [[ ${__pkg} == "config" && $(dmidecode -s chassis-type) != "Laptop" ]]; then
        cp -r ./${__pkg}/* ${ROOT_CONFIG_PATH}/
        cp -r ./${__pkg}/* ${USER_CONFIG_PATH}/
        chown -R ${LOCAL_USER}:${LOCAL_USER} ${USER_CONFIG_PATH}/

      elif [[ ${__pkg} == "config_laptop" && $(dmidecode -s chassis-type) == "Laptop" ]]; then
        cp -r ./${__pkg}/* ${ROOT_CONFIG_PATH}/
        cp -r ./${__pkg}/* ${USER_CONFIG_PATH}/
        chown -R ${LOCAL_USER}:${LOCAL_USER} ${USER_CONFIG_PATH}/

      elif [[ ${__pkg} == "fonts" ]]; then
        cp -r ./${__pkg}/* ${FONTS_DIR}/

      elif [[ ${__pkg} == "smplayer-icons" ]]; then
        cp -r ./${__pkg}/* ${SMPLAYER_THEME_DIR}/
        chmod 755 ${SMPLAYER_THEME_DIR}/Papirus
        chmod 644 ${SMPLAYER_THEME_DIR}/Papirus/*
        chmod 755 ${SMPLAYER_THEME_DIR}/PapirusDark
        chmod 644 ${SMPLAYER_THEME_DIR}/PapirusDark/*
        chmod 755 ${SMPLAYER_THEME_DIR}/ePapirus
        chmod 644 ${SMPLAYER_THEME_DIR}/ePapirus/*

      elif [[ ${__pkg} == "wallpappers" ]]; then
        cp -r ./${__pkg}/* ${WALLPAPPERS_DIR}/
        cp -r ./${__pkg}/* ${USER_PICTURES_PATH}/
        chown -R ${LOCAL_USER}:${LOCAL_USER} ${USER_PICTURES_PATH}/
        chmod 644 ${WALLPAPPERS_DIR}/*

      elif [[ ${__pkg} == "deno" ]]; then
        cp -r ./${__pkg}/* ${LOCAL_BIN}/
        chown -R ${LOCAL_USER}:${LOCAL_USER} ${LOCAL_BIN}
        chmod +x ${LOCAL_BIN}/${__pkg}

      elif [[ ${__pkg} == "bun" ]]; then
        cp -r ./${__pkg}/* ${LOCAL_BIN}/
        chown -R ${LOCAL_USER}:${LOCAL_USER} ${LOCAL_BIN}
        chmod +x ${LOCAL_BIN}/${__pkg}

      elif [[ ${__pkg} == "selene" ]]; then
        cp -r ./${__pkg}/* ${LOCAL_BIN}/
        chown -R ${LOCAL_USER}:${LOCAL_USER} ${LOCAL_BIN}
        chmod +x ${LOCAL_BIN}/${__pkg}

      elif [[ ${__pkg} == "yt-dlp" ]]; then
        cp -r ./${__pkg}/* ${LOCAL_BIN}/
        chown -R ${LOCAL_USER}:${LOCAL_USER} ${LOCAL_BIN}
        chmod +x ${LOCAL_BIN}/${__pkg}
        su - -c "${LOCAL_BIN}/${__pkg} -U" ${LOCAL_USER}

      elif [[ ${__pkg} == "vimix-icon-theme" ]]; then
        chmod +x ./${__pkg}/${__pkg}-master/install.sh
        ./${__pkg}/${__pkg}-master/install.sh doder

      elif [[ ${__pkg} == "grub2-themes" ]]; then
        chmod +x ./${__pkg}/install.sh
        ./${__pkg}/install.sh -t vimix -i white -s 1080p -g ${GRUB_THEME_DIR}/

        echo "#!/bin/bash

              if [[ \$(id -u) != "0" ]]; then
                echo "Use sudo!"
              fi

              sed -i 's/Unifont Regular 16/Terminus Regular 16/g' ${GRUB_THEME_DIR}/vimix/theme.txt
              sed -i 's/^GRUB_THEME/# GRUB_THEME/' ${GRUB_CFG_PATH}
              sed -i 's/^GRUB_TIMEOUT/# GRUB_TIMEOUT/' ${GRUB_CFG_PATH}
              sed -i 's/^GRUB_BACKGROUND/# GRUB_BACKGROUND/' ${GRUB_CFG_PATH}
              sed -i 's/^GRUB_WALLPAPER/# GRUB_WALLPAPER/' ${GRUB_CFG_PATH}
              
              echo \"
              GRUB_THEME=${GRUB_THEME_DIR}/vimix/theme.txt
              GRUB_TIMEOUT=3\" >> ${GRUB_CFG_PATH}
              " | sed 's/^[ ]*//' >> ${FIX_GRUB_PATH}

        if [[ $(dmidecode -s chassis-type) == "Laptop" && ${ENABLE_LAPTOP} == "true" ]]; then
          __cpu_name=$(cat /proc/cpuinfo | grep "vendor_id" | uniq | awk '{print $3}')
          if [[ ${__cpu_name} == "GenuineIntel" ]]; then
              echo -e "sed -i '/LINUX_DEFAULT/s/splash/splash intel_pstate=disable/' ${GRUB_CFG_PATH}\n" >> ${FIX_GRUB_PATH}
          fi
        fi

        echo "update-grub" >> ${FIX_GRUB_PATH}

        chmod 755 ${FIX_GRUB_PATH}
        \. ${FIX_GRUB_PATH}

      elif [[ ${__pkg} == "plymouth-themes" ]]; then
        cp -r ./${__pkg}/pack_1/circle ${PLYMOUTH_THEME_DIR}/
        plymouth-set-default-theme -R circle
        
      elif [[ ${__pkg} == "shadowsocks" ]]; then
        __ss_list=($(ls -A ./${__pkg}))
        for __file in ${__ss_list[@]}
        do
          cp -r ./${__pkg}/${__file} ${SYSTEM_BIN}/
          chmod +x ${SYSTEM_BIN}/${__file}
        done
        echo "{
                \"server\": \"${SSLOCAL_REMOTE_IP}\",
                \"mode\": \"tcp_and_udp\",
                \"server_port\": ${SSLOCAL_REMOTE_PORT},
                \"local_address\": \"${SSLOCAL_LOCAL_IP}\",
                \"local_port\": ${SSLOCAL_LOCAL_PORT},
                \"password\": \"${SSLOCAL_PASSSWORD}\",
                \"timeout\": 300,
                \"method\": \"aes-256-gcm\",
                \"fast_open\": false,
                \"workers\": 1,
                \"prefer_ipv6\": true
              }" | sed -E 's/^[ ]{14}//mg;t' >> ${SS_CONFIG_DIR}/${SSLOCAL_NAME}.json
        echo "[Unit]
              Description=Daemon to start Shadowsocks Client
              Wants=network-online.target
              After=network.target
              [Service]
              Type=simple
              ExecStart=${SYSTEM_BIN}/sslocal -c ${SS_CONFIG_DIR}/${SSLOCAL_NAME}.json
              [Install]
              WantedBy=multi-user.target" | sed 's/^[ ]*//' >> /etc/systemd/system/sslocal.service
        systemctl daemon-reload
        systemctl enable sslocal.service

      elif [[ ${__pkg} == "ssh" ]]; then
        __key_list=($(ls -A ./${__pkg}))
        for __file in ${__key_list[@]}
        do
          cp -r ./${__pkg}/${__file} ${SSH_DIR}/
          chown -R ${LOCAL_USER}:${LOCAL_USER} ${SSH_DIR}
          chmod 600 ${SSH_DIR}/${__file}
        done
        echo "Host gitflic
              host gitflic.ru
              IdentityFile ${SSH_DIR}/gitflic.ru

              Host github
              host github.com
              IdentityFile ${SSH_DIR}/github.com

              Host gitverse
              host gitverse.ru
              IdentityFile ${SSH_DIR}/gitverse.ru" | sed 's/^[ ]*//' >> ${SSH_DIR}/config
      fi
    fi
  done
}

# tweaks
function tweaks() {
  if [[ $(cinnamon --version | sed 's/[^a-zA-Z].*//') == ?innamon ]]; then
    if [[ -f /etc/lightdm/slick-greeter.conf ]]; then
      mv /etc/lightdm/slick-greeter.conf /etc/lightdm/slick-greeter.conf.bak
    fi
    echo "[Greeter]
    background=${WALLPAPPERS_DIR}/mountain.jpg
    theme-name=Arc-Lighter
    icon-theme-name=Vimix-doder
    cursor-theme-name=DMZ-Black" | sed 's/^[ ]*//' > /etc/lightdm/slick-greeter.conf
  fi
  echo "alias apt='sudo apt-get'
        alias yt='yt-dlp'
        alias reboot='systemctl reboot'" | sed 's/^[ ]*//' >> ${USER_PROFILE_PATH}
  echo "export EDITOR=micro" >> /etc/profile.d/editor.sh
  chmod +x /etc/profile.d/editor.sh
  usermod ${LOCAL_USER} -aG docker
  systemctl enable docker
  su - -c "git config --global user.name ${GIT_NAME}" ${LOCAL_USER}
  su - -c "git config --global user.email ${GIT_EMAIL}" ${LOCAL_USER}
  echo "[Appearance]
        Font=JetBrainsMono Nerd Font,10,-1,5,50,0,0,0,0,0

        [General]
        Command=/bin/bash --login
        Name=user
        Parent=FALLBACK/
        TerminalColumns=115
        TerminalRows=24
        " | sed 's/^[ ]*//' >> ${KONSOLE_CONFIG_PATH}/user.profile
  chown -R ${LOCAL_USER}:${LOCAL_USER} ${KONSOLE_CONFIG_PATH}/user.profile

  if [[ $(dmidecode -s chassis-type) == "Laptop" && ${ENABLE_LAPTOP} == "true" ]]; then
    echo -e "devices/system/cpu/cpufreq/boost = ${BOOST}\n" >> /etc/sysfs.conf
    for ((i = 0; i < $(nproc); i++))
    do
      echo "devices/system/cpu/cpu${i}/cpufreq/scaling_min_freq = ${MIN_FREQ}
            devices/system/cpu/cpu${i}/cpufreq/scaling_max_freq = ${MAX_FREQ}
            devices/system/cpu/cpu${i}/cpufreq/scaling_governor = ${GOVERNOR}
            " | sed 's/^[ ]*//' >> /etc/sysfs.conf
    done
    systemctl enable sysfs.service
    systemctl disable cpufreq-simple.service
  fi

  timedatectl set-local-rtc 1 --adjust-system-clock

  # Fix Alacritty icon
  sed -i '/Icon/s/Alacritty/\/usr\/share\/icons\/hicolor\/scalable\/Alacritty.svg/' /usr/share/applications/Alacritty.desktop
}

# set dconf
function set_dconf {
  __type_device=$(dmidecode -s chassis-type)
  __font_size=""
  if [[ ${__type_device} == "Laptop" ]]; then
    __font_size="9"
  else
    __font_size="10"
  fi
  __pid_session=$(pgrep cinnamon-sessio)
  __bus_address=$(strings /proc/${__pid_session}/environ | grep DBUS_SESSION_BUS_ADDRESS | sed 's/.*[=]\b//')
  su - -c "export LOCAL_USER=${LOCAL_USER};
           export USER_PICTURES_PATH=${USER_PICTURES_PATH};
           export DBUS_SESSION_BUS_ADDRESS=${__bus_address};
           export FONT_SIZE=${__font_size};
           export TYPE_DEVICE=${__type_device};
           ${SELF_PATH}/${ID}/${ID}_dconf.sh" ${LOCAL_USER}

  export TYPE_DEVICE=${__type_device}
  export FONT_SIZE=${__font_size}
  \. ${SELF_PATH}/${ID}/${ID}_dconf.sh
}

# Install extras (nvm,rvm)
function install_extras {
  su - -c "export USER_PROFILE_PATH=${USER_PROFILE_PATH};
           export PROFILE=/dev/null;
           ${SELF_PATH}/extras.sh" ${LOCAL_USER}
}

make_dirs
prepare
download_files
install_ext_rpms
extract
move_configs
tweaks
set_dconf
install_extras
clean_temp_dir
